<template>
	<view>
		<view class="cu-list menu-avatar">
			<view class="cu-item" :class="modalName=='move-box-'+ index?'move-cur':''" v-for="(item,index) in chatBoxList" :key="index"
			 @touchstart="ListTouchStart" @touchmove="ListTouchMove" @touchend="ListTouchEnd" :data-target="'move-box-' + index"
			 @tap="tapOne(item)">
				<view class="cu-avatar round lg" :style="[{backgroundImage:'url('+item.friendFaceImage+')'}]">
					<view class="cu-tag badge" v-if="!item.isRead">1+</view>
				</view>
				<view class="content">
					<view class="text-grey">{{item.friendUsername}}</view>
					<view class="text-gray text-sm flex">
						<view class="text-cut">
							{{item.msg}}
						</view>
					</view>
				</view>
				<view class="action">
					<view class="text-grey text-xs">{{item.time}}</view>
					<!-- <view v-if="item.isRead" class="cu-tag round bg-grey sm">{{item.count}}</view> -->
				</view>
				<view class="move">
					<view class="bg-grey" @tap.stop="setFirst(item)">置顶</view>
					<view class="bg-red" @tap.stop="delDialog(item)">删除</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		onShow() {
			console.log('onShow');
			this.loadingChatSnapShot();

			/*
				TODO 当收到好友上线后，1.进行通知。2.将用户的头像点亮
			*/
			var that = this
			that.$tool.WEBSOCKET._callbacks.message = [function(e) {
				var msg = (JSON.parse(e.data)).chatMsg.msg
				var sendUserId = (JSON.parse(e.data)).chatMsg.sendUserId
				var time = that.$tool.getNowDate()
				var userId = that.$tool.getStorageSync('userInfo').id
				// 接收到的 '消息快照' 保存为 "未读" false
				that.$tool.saveChatSnapShot(userId, sendUserId, msg, false, time)

				// 将接收到的聊天消息保存到 localStorage 中
				that.$tool.saveChatHistory(userId, sendUserId, msg, time, 1) // 发送者ID，接收者ID，消息,时间

				// 重新渲染聊天快照
				that.loadingChatSnapShot();
			}]
		},
		onHide() {
			console.log('onhide')

			// 重新设置websocket的onMessage处理函数
			var that = this
			this.$tool.WEBSOCKET._callbacks.message = [function(e) {
				var msg = (JSON.parse(e.data)).chatMsg.msg
				var sendUserId = (JSON.parse(e.data)).chatMsg.sendUserId
				var time = that.$tool.getNowDate()
				var userId = that.$tool.getStorageSync('userInfo').id

				// 接收到的 '消息快照' 保存为 "未读" false
				that.$tool.saveChatSnapShot(userId, sendUserId, msg, false, time)

				// 将接收到的聊天消息保存到 localStorage 中
				that.$tool.saveChatHistory(userId, sendUserId, msg, time, 1) // 发送者ID，接收者ID，消息,时间
			}]
		},
		onLoad() {
			this.userInfo = this.$tool.getStorageSync('userInfo')
			this.initWebSocket(); // 建立 websocket 连接
		},
		onUnload() {
			console.log('首页：onUnLoad')
		},
		data() {
			return {
				modalName: null,
				userInfo: null,
				chatBoxList: []
			}
		},
		methods: {

			// 初始化 WebSocket,将 SocketTask 实例放入 this.$tool工具实例中
			initWebSocket() {

				// 1、建立 websocket 连接
				var websocket = uni.connectSocket({
					url: this.$tool.nettyURL,
					success: () => {
						console.log('创建一个 WebSocket 连接。')
					}
				})
				
				// 2、监听 websocket 连接打开
				websocket.onOpen((data) => {
					console.log('WebSocket 连接打开')
					// 构建chatMsg
					var chatMsg = new this.$tool.ChatMsg(this.userInfo.id, null, this.userInfo.id + '+' + this.userInfo.username,
						null)
					// 构建dataContent
					var dataContent = new this.$tool.DataContent(this.$tool.CONNECT, chatMsg, null)
					// websocket 发送消息 [用户已上线！]
					websocket.send({
						data: JSON.stringify(dataContent)
					})
					// 像服务端获取用户未签收的消息
					this.getUserNotReadHistory()
				})
				
				// 3、监听 websocket 连接关闭
				websocket.onClose((errMsg) => {
					console.log('WebSocket 连接关闭')
				})

				this.$tool.WEBSOCKET = websocket // 向工具类实例中放websocket实例
			},
			
			// 向服务端获取用户A上次下线后错过的所有消息
			async getUserNotReadHistory() {
				// 1、拿到所有未读消息
				var res = await this.$request({
					baseURL: this.$tool.serverURL,
					url: 'front/message/getUnReadMsgList',
					params: {
						acceptUserId: this.userInfo.id
					},
					type: 'get'
				})
				console.log('res',res)
				
				var msgListId = [] // 待签收消息ID
				
				// 2、更新用户的各个聊天记录
				var chatHistoryObj = {}
				res.data.forEach(val => {
					msgListId.push(val.id)
					this.$tool.saveChatHistory(val.acceptUserId,val.sendUserId,val.message,val.gmtCreate,1) // 把每一条未读消息保存到缓存中对应的聊天记录中
					// 3、更新用户的各个聊天快照为未签收
					this.$tool.saveChatSnapShot(val.acceptUserId, val.sendUserId, val.message, false, val.gmtCreate)
				})
				
				// 4、重新渲染聊天快照
				this.loadingChatSnapShot()
				
				// 5、服务端标记聊天记录为——已签收
				var dataContent = new this.$tool.DataContent(this.$tool.SIGNED, null, msgListId)
				console.log('dataContent',dataContent);
				console.log('websocket',this.$tool.WEBSOCKET);
				this.$tool.WEBSOCKET.send({
					data: JSON.stringify(dataContent),
					success:function() {
						console.log('批量签收！')
					},
					fail: function() {
						that.$tool.sendToast('websocket-消息发送失败！')
					}
				})
			},
			
			// 加载用户与其他朋友聊天的 “聊天快照”
			loadingChatSnapShot() {
				var that = this
				var snapShotList = this.$tool.getChatSnapShot(this.userInfo.id)
				var chatList = []
				// 遍历聊天快照list
				snapShotList.forEach(shotItem => {
					var foo = {}
					var friendUserId = shotItem.friendUserId //拿到联系人id
					Object.assign(foo, shotItem)
					foo.time = that.$tool.snapTimeFormat(shotItem.time)
					Object.assign(foo, that.$tool.getFriendInfoFromContactList(friendUserId)) // 拿到联系人信息[浅拷贝]
					chatList.push(foo)
				})
				this.chatBoxList = chatList
			},

			// ListTouch触摸开始
			ListTouchStart(e) {
				this.listTouchStart = e.touches[0].pageX
			},

			// ListTouch计算方向
			ListTouchMove(e) {
				this.listTouchDirection = e.touches[0].pageX - this.listTouchStart > 0 ? 'right' : 'left'
			},

			// ListTouch计算滚动
			ListTouchEnd(e) {
				if (this.listTouchDirection == 'left') {
					this.modalName = e.currentTarget.dataset.target
				} else {
					this.modalName = null
				}
				this.listTouchDirection = null
			},

			// 聊天框置顶
			setFirst(dialog) {

				for (var i = 0; i < this.chatBoxList.length; i++) {
					if (this.chatBoxList[i] === dialog) {
						this.chatBoxList.splice(i, 1);
						break;
					}
				}
				this.chatBoxList.unshift(dialog);

			},

			// 删除聊天框
			delDialog(dialog) {
				this.$tool.delSnapChatShot(dialog.userId,dialog.friendUserId)
				this.loadingChatSnapShot();
			},

			// 点击
			tapOne(user) {
				this.$tool.ReadSnapChatShot(user.userId, user.friendUserId) // 更改该条消息快照为已读
				var {
					friendUserId,
					friendUsername,
					friendNickname,
					friendFaceImage
				} = user
				var foo = {
					friendUserId,
					friendUsername,
					friendNickname,
					friendFaceImage
				}
				uni.navigateTo({
					url: `../chat/chat?user=${encodeURIComponent(JSON.stringify(foo))}`
				})
			}
		}
	}
</script>

<style>
</style>
